import React, { useState, useEffect, useRef, useMemo } from 'react'
import TweenOne from 'rc-tween-one'
import { useSelector, useDispatch } from 'react-redux'

import scss from './index.module.scss'
import { getBoundingClientRect } from '@/util/common.js'

const Drawer = ({ pos = 'left', children = null, width = 200 }) => {
  const visible = useSelector((store) => store.aside.visible)
  const dispatch = useDispatch()

  const drawerRef = useRef()

  const [style, setStyle] = useState(getStyle())
  const [moveX, setMoveX] = useState(0)
  const [ani, setAni] = useState({
    paused: true,
    reverse: false,
  })

  useEffect(() => {
    setStyle(getStyle())
    _setMoveX()
  }, [pos])

  useEffect(() => {
    visible ? setAni({ paused: false, reverse: true }) : setAni({ paused: false, reverse: false })
  }, [visible])

  useMemo(() => {
    dispatch({ type: 'setAsideWidth', pos, width: Math.abs(moveX).toFixed(2) })
  }, [moveX])

  function getStyle() {
    return pos === 'left'
      ? {
          boxShadow: '3px 0px 6px #DADFE9',
        }
      : {
          boxShadow: '-3px 0px 6px #DADFE9',
        }
  }

  function _setMoveX() {
    const { width } = getBoundingClientRect(drawerRef.current)
    const val = pos === 'left' ? -1 : 1
    setMoveX(width * val)
  }

  return (
    <TweenOne
      animation={{
        x: moveX,
        duration: 350,
      }}
      paused={ani.paused}
      reverse={ani.reverse}
      className={scss.drawer}
      style={{ ...style, width }}
    >
      <div ref={drawerRef}>{children}</div>
    </TweenOne>
  )
}

export default Drawer
